// articleMixin.js：文章管理组件的逻辑混入
import {
  getArticleList,
  getCategoryList,
  submitReview,
  aiCheck,
  statusMap,
  createCategoryMap,
  actionMap,
  getCategoryTagType,
  getStatusTagType,
  canReview,
  canBan,
  canDelete
} from '@/api/article'

export default {
  data() {
    return {
      loading: false,
      submitting: false,
      detailVisible: false,
      isFullscreen: false,
      reviewVisible: false,
      articleList: [],
      articleDetail: null,
      categoryList: [],
      total: 0,
      searchForm: {
        page: 1,
        pageSize: 10,
        category_id: '',
        keyWords: '',
        status: ''
      },
      reviewForm: {
        id: '',
        reviewMessage: '',
        status: 0,
        type: 1
      },
      // AI审核相关数据
      selectedArticles: [],
      aiReviewVisible: false,
      aiReviewResults: [],
      submittingReview: false
    }
  },
  computed: {
    categoryOptions() {
      return createCategoryMap(this.categoryList)
    },
    statusOptions() {
      return statusMap
    },
    dialogTitle() {
      return actionMap[this.reviewForm.status] || '操作确认'
    },
    selectedReviewResults() {
      return this.aiReviewResults.filter(result => result.selected)
    }
  },
  mounted() {
    this.getCategoryList()
    this.getArticleList()
  },
  methods: {
    async getCategoryList() {
      try {
        const result = await getCategoryList()
        if (result?.code === 1) {
          this.categoryList = result.data || []
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    },
    async getArticleList() {
      this.loading = true
      try {
        const result = await getArticleList(this.searchForm)
        if (result?.code === 1) {
          const data = result.data || {}
          // 根据API文档，数据在records字段中
          this.articleList = data.records || []
          // 总数在total字段中
          this.total = data.total || 0
        } else {
          // 处理API返回错误的情况
          this.articleList = []
          this.total = 0
          console.warn('获取文章列表失败:', result?.msg || '未知错误')
        }
      } catch (error) {
        console.error('获取文章列表异常:', error)
        this.articleList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.searchForm.page = 1
      this.getArticleList()
    },
    handleReset() {
      this.searchForm = { page: 1, pageSize: 10, category_id: '', keyWords: '', status: '' }
      this.getArticleList()
    },
    async viewDetail(row) {
      this.loading = true
      try {
        // 直接使用列表中的数据，确保数据一致性
        this.articleDetail = { ...row }
        this.detailVisible = true
        this.isFullscreen = false // 重置全屏状态
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
    },
    formatContent(content) {
      if (!content) return ''

      // 使用正则表达式处理Markdown格式
      let formattedContent = content

      // 处理图片链接 - 将 ![alt](url) 格式转换为标注
      formattedContent = formattedContent.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,
        '<div class="markdown-image-link"><i class="el-icon-picture"></i> 图片链接: $1 <span class="image-url">$2</span></div>')

      // 处理一级标题 # 标题
      formattedContent = formattedContent.replace(/^# (.+)$/gm, '<h1 class="markdown-h1">$1</h1>')

      // 处理二级标题 ## 标题
      formattedContent = formattedContent.replace(/^## (.+)$/gm, '<h2 class="markdown-h2">$1</h2>')

      // 处理三级标题 ### 标题
      formattedContent = formattedContent.replace(/^### (.+)$/gm, '<h3 class="markdown-h3">$1</h3>')

      // 处理四级标题 #### 标题
      formattedContent = formattedContent.replace(/^#### (.+)$/gm, '<h4 class="markdown-h4">$1</h4>')

      // 处理粗体 **文本**
      formattedContent = formattedContent.replace(/\*\*([^*]+)\*\*/g, '<strong class="markdown-bold">$1</strong>')

      // 处理斜体 *文本*
      formattedContent = formattedContent.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em class="markdown-italic">$1</em>')

      // 处理行内代码 `代码`
      formattedContent = formattedContent.replace(/`([^`]+)`/g, '<code class="markdown-inline-code">$1</code>')

      // 处理代码块 ```代码```
      formattedContent = formattedContent.replace(/```([\s\S]*?)```/g, '<pre class="markdown-code-block"><code>$1</code></pre>')

      // 处理链接 [文本](url)
      formattedContent = formattedContent.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="markdown-link" target="_blank">$1</a>')

      // 处理段落 - 将连续的非空行转换为段落
      formattedContent = formattedContent.replace(/^(?!<[h1-4]|<div|<pre|<ul|<ol)(.+)$/gm, function(match, p1) {
        // 跳过已经处理过的元素
        if (match.includes('<') && (match.includes('h1') || match.includes('h2') || match.includes('h3') || match.includes('h4') ||
            match.includes('div') || match.includes('pre') || match.includes('ul') || match.includes('ol'))) {
          return match
        }
        return '<p class="markdown-paragraph">' + p1 + '</p>'
      })

      // 处理换行 - 将单个换行转换为<br>
      formattedContent = formattedContent.replace(/\n\n/g, '<br><br>')
      formattedContent = formattedContent.replace(/\n(?!<)/g, '<br>')

      return formattedContent
    },
    getCategoryLabel(categoryId) {
      const categoryMap = createCategoryMap(this.categoryList)
      return categoryMap[categoryId] || categoryId
    },
    getStatusLabel(status) {
      return statusMap[status] || status
    },
    getCategoryTagType,
    getStatusTagType,
    canReview,
    canBan,
    canDelete,
    handleReview(row) {
      this.reviewForm = {
        id: row.articleId,
        reviewMessage: '',
        status: 0,
        type: 1
      }
      this.reviewVisible = true
    },
    handleBan(row) {
      this.reviewForm = {
        id: row.articleId,
        reviewMessage: '',
        status: 6,
        type: 1
      }
      this.reviewVisible = true
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getArticleList()
    },
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getArticleList()
    },
    handleDelete(row) {
      this.reviewForm = {
        id: row.articleId,
        reviewMessage: '',
        status: 7,
        type: 1
      }
      this.reviewVisible = true
    },
    handleApprove() {
      this.reviewForm.status = 2
      this.submitReview()
    },
    handleReject() {
      this.reviewForm.status = 5
      this.submitReview()
    },
    async submitReview() {
      // 验证必填字段
      if (!this.reviewForm.id) {
        this.$message.error('文章ID不能为空')
        return
      }

      if (!this.reviewForm.reviewMessage) {
        this.$message.error('请填写操作原因')
        return
      }

      this.submitting = true
      try {
        // 确保提交的数据结构正确，包含所有必要字段
        const submitData = {
          id: this.reviewForm.id,
          type: this.reviewForm.type || 1,
          reviewMessage: this.reviewForm.reviewMessage || '',
          status: this.reviewForm.status
        }

        console.log('提交审核数据:', submitData) // 调试日志
        const result = await submitReview(submitData)
        if (result?.code === 1) {
          this.$message.success('操作成功')
          this.reviewVisible = false
          this.getArticleList() // 刷新列表
        } else {
          this.$message.error(result?.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交审核失败:', error)
        this.$message.error('操作失败，请重试')
      } finally {
        this.submitting = false
      }
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      try {
        const date = new Date(dateTime)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      } catch (error) {
        return dateTime
      }
    },
    getImageUrls() {
      if (!this.articleDetail || !this.articleDetail.imgUrls) {
        return []
      }

      try {
        // 尝试解析JSON字符串
        if (typeof this.articleDetail.imgUrls === 'string') {
          const urls = JSON.parse(this.articleDetail.imgUrls)
          return Array.isArray(urls) ? urls : []
        }

        // 如果已经是数组，直接返回
        if (Array.isArray(this.articleDetail.imgUrls)) {
          return this.articleDetail.imgUrls
        }

        return []
      } catch (error) {
        console.warn('解析图片URLs失败:', error)
        return []
      }
    },
    // AI审核相关方法
    handleSelectionChange(selection) {
      this.selectedArticles = selection
    },
    async handleAiCheck() {
      if (this.selectedArticles.length === 0) {
        this.$message.warning('请先选择要审核的文章')
        return
      }

      const articleIds = this.selectedArticles.map(article => article.articleId)

      try {
        this.loading = true
        const result = await aiCheck(articleIds)

        if (result?.code === 1) {
          // 为每个审核结果添加选中状态
          this.aiReviewResults = (result.data || []).map(item => ({
            ...item,
            selected: true // 默认全部选中
          }))
          this.aiReviewVisible = true
        } else {
          this.$message.error(result?.msg || 'AI审核失败')
        }
      } catch (error) {
        console.error('AI审核失败:', error)
        this.$message.error('AI审核失败，请重试')
      } finally {
        this.loading = false
      }
    },
    handleReviewItemChange() {
      // 当审核项选择状态改变时的处理
    },
    getArticleTitle(articleId) {
      const article = this.articleList.find(item => item.articleId === articleId)
      return article ? article.title : `文章ID: ${articleId}`
    },
    getReviewStatusLabel(status) {
      const statusLabels = {
        1: '通过',
        2: '通过',
        3: '拒绝',
        4: '待审核',
        5: '拒绝'
      }
      return statusLabels[status] || '未知'
    },
    getReviewStatusTagType(status) {
      const typeMap = {
        1: 'success',
        2: 'success',
        3: 'danger',
        4: 'warning',
        5: 'danger'
      }
      return typeMap[status] || 'info'
    },
    async submitAiReview() {
      if (this.selectedReviewResults.length === 0) {
        this.$message.warning('请选择要提交的审核结果')
        return
      }

      this.submittingReview = true
      try {
        // 构建提交数据，只提交选中的审核结果
        const submitData = this.selectedReviewResults.map(result => ({
          id: result.id,
          type: result.type,
          reviewMessage: result.reviewMessage,
          status: result.status
        }))

        const result = await submitReview(submitData)
        if (result?.code === 1) {
          this.$message.success(`成功提交 ${submitData.length} 条审核结果`)
          this.aiReviewVisible = false
          this.aiReviewResults = []
          this.selectedArticles = []
          this.getArticleList() // 刷新列表
        } else {
          this.$message.error(result?.msg || '提交审核失败')
        }
      } catch (error) {
        console.error('提交审核失败:', error)
        this.$message.error('提交审核失败，请重试')
      } finally {
        this.submittingReview = false
      }
    }
  }
}
